package com.netcracker.ui.command;

import com.netcracker.entity.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.UserService;
import com.netcracker.util.service.exception.NullDataException;
import com.netcracker.util.service.exception.DataTransmittingException;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AuthorizationCommand implements Command {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationCommand.class);
private final ServiceFacade serviceFacade;

    public AuthorizationCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        
        if (request.getParameter("username") != null && request.getParameter("password") != null) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if (!username.isEmpty() && !password.isEmpty()) {
                UserService userService = serviceFacade.getUserService();
                try {
                    User user = userService.authorize(username, password);
                    HttpSession session = request.getSession(true);
                    session.setAttribute("user", user.getLogin());
                    session.setAttribute("right", user.getRight());
                    session.setAttribute("id", user.getId());
                    LOGGER.info("User authorized: ", username);
                } catch (DataTransmittingException ex) {
                    request.setAttribute("error", "Ошибка обращения к БД.");
                    LOGGER.error("DB error: ", ex);
                } catch (NoSuchAlgorithmException ex) {
                    LOGGER.error(ex.getMessage(), ex);
                } catch (NullDataException ex) {
                    request.setAttribute("errorLogin", "Неверное имя пользователя или пароль.");
                    LOGGER.error("User enter wrong login or password: ", ex);
                }
            } else {
                request.setAttribute("errorLogin", "Введите логин и пароль.");
            }
        }
        return "index.jsp";
    }
}